package com.example.scg.route.generator.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotNull;
import lombok.Builder;
import lombok.Data;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatus.Series;

/**
 * Retry默认配置类
 *
 * CreateTime: 2020-01-12
 *
 * @author HuangZhongHui
 **/
@Data
@Builder
public class RetryConfig {

  private int retries;
  private List<Series> series;
  private List<HttpStatus> statuses;
  private List<HttpMethod> methods;
  private List<Class<? extends Throwable>> exceptions;
  private BackoffConfig backoff;

  /**
   * 填充配置参数到args map中
   */
  public void fillConfMap(@NotNull Map<String, String> args) {
    if (this.retries > 0) {
      args.put("retries", String.valueOf(retries));
    }
    if (series != null && series.size() > 0) {
      series.stream().map(Enum::name)
          .reduce((s1, s2) -> s1 + "," + s2)
          .ifPresent(s -> args.put("series", s));
    }
    if (statuses != null && statuses.size() > 0) {
      statuses.stream().map(Enum::name)
          .reduce((s1, s2) -> s1 + "," + s2)
          .ifPresent(s -> args.put("statuses", s));
    }
    //TODO 目前仅支持GET
    if (methods != null && methods.size() > 0) {
      args.put("methods", HttpMethod.GET.name());
    }
    if (exceptions != null && exceptions.size() > 0) {
      exceptions.stream().map(Class::getSimpleName)
          .reduce((s1, s2) -> s1 + "," + s2)
          .ifPresent(s -> args.put("exceptions", s));
    }
    if (backoff != null) {
      backoff.fillConfMap(args);
    }
  }

  @SafeVarargs
  public static <T> List<T> toList(T... items) {
    return new ArrayList<>(Arrays.asList(items));
  }
}
